package com.zhang.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.security.mapper.UserMapper;
import com.zhang.security.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("userDetailsService")//给这个组件起个名字,必须和配置类里面自动注入的一样  回忆spring
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据库得到用户的密码
        QueryWrapper<Users> wrapper= new QueryWrapper<>();
        wrapper.eq("username",username);
        Users user = userMapper.selectOne(wrapper);

        if (user==null){
            //查无此用户
            throw new  UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,manager1");
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}
